import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbclass, tbstudent } from '../../../../../atoms/db';
import getuser from '../../../../../atoms/getuser';

const logger = anylogger('pages/api/class/add/list/add.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	class_id: string;
	student_id: string;
}

/**
 * pages/api/class/add/list/add.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const user = await getuser(req);
		if (!user || user.role !== 'admin') {
			res.status(200).json({
				ok: false,
				message: '没有权限'
			});
			return;
		}
		const { class_id, student_id } = req.body as Message;
		if (!class_id || !student_id) {
			res.status(200).json({ ok: false, message: '编号为空' });
			return;
		}
		const student = await tbstudent()
			.first('class_id')
			.where({
				student_id
			});
		if (!student) {
			res.status(200).json({ ok: false, message: '学生不存在' });
			return;
		}
		const cls = await tbclass()
			.first('*')
			.where({
				class_id
			});
		if (!cls) {
			res.status(200).json({ ok: false, message: '班级不存在' });
			return;
		}
		// if(student.classnumber)
		await tbstudent()
			.update({
				class_id,
				majorname: cls.majorname,
				grade: cls.grade,
				classname: cls.classname
			})
			.where({ student_id });
		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
